package com.it.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.reggie.annotation.Log;
import com.it.reggie.commen.R;
import com.it.reggie.entity.*;
import com.it.reggie.service.*;
import com.it.reggie.utils.ExcelUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
@SuppressWarnings(value = "all")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private ShoppingCartService shoppingCartService;

//    @Autowired
//    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;


    @Log("用户进行了下单操作")
    @PostMapping("/submit")
    /*
    需要手动设置的数据
    下单用户id
    number:订单号
    时间
    订单状态
    订单金额
    ...
     */
    public R submit(@RequestBody Orders orders, HttpServletRequest request) {

        //获取用户id
        Long userId = (Long) request.getSession().getAttribute("user");

        //ShoppingCart的条件构造器
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        //获取购物车的数据
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        //设置总金额
        BigDecimal amount = new BigDecimal("0");
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            BigDecimal price = shoppingCart.getAmount();
            Integer number1 = shoppingCart.getNumber();
            BigDecimal number = new BigDecimal(String.valueOf(BigDecimal.valueOf(number1)));
            orderDetail.setAmount(price.multiply(number));

            amount = amount.add(orderDetail.getAmount());


            Long setmealId = shoppingCart.getSetmealId();
            if (setmealId != null) {
                orderDetail.setSetmealId(setmealId);
            } else {
                orderDetail.setDishId(shoppingCart.getDishId());
            }
            orderDetails.add(orderDetail);
        }
        LambdaQueryWrapper<AddressBook> bookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bookLambdaQueryWrapper.eq(AddressBook::getUserId, userId).eq(AddressBook::getIsDefault, 1);
        AddressBook addressBookServiceOne = addressBookService.getOne(bookLambdaQueryWrapper);

        //给orders里面的属性赋值
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDate.now());
        orders.setUserId(userId);
        orders.setAmount(amount);
        orders.setNumber(String.valueOf(IdWorker.getId()));
        orders.setConsignee(addressBookServiceOne.getConsignee());
        orders.setPhone(addressBookServiceOne.getPhone());
        orders.setUserName(addressBookServiceOne.getConsignee());
        orders.setAddress(
                (addressBookServiceOne.getProvinceName() == null ? "" : addressBookServiceOne.getProvinceName())
                        + (addressBookServiceOne.getCityName() == null ? "" : addressBookServiceOne.getCityName())
                        + (addressBookServiceOne.getDistrictName() == null ? "" : addressBookServiceOne.getDistrictName())
                        + (addressBookServiceOne.getDetail() == null ? "" : addressBookServiceOne.getDetail()));

        ordersService.save(orders);

        for (OrderDetail orderDetail : orderDetails) {

            orderDetail.setOrderId(orders.getId());

        }

        orderDetailService.saveBatch(orderDetails);

        //清空购物车
        LambdaQueryWrapper<ShoppingCart> queryWrapper1 = new LambdaQueryWrapper<>();

        queryWrapper1.eq(ShoppingCart::getUserId, userId);

        shoppingCartService.remove(queryWrapper1);

        return R.success("清空购物车成功");

    }

    @GetMapping("/userPage")
    public R selectByUserPage(Integer page, Integer pageSize, HttpServletRequest request) {

        IPage<Orders> iPage = new Page<>(page, pageSize);

        Long userId = (Long) request.getSession().getAttribute("user");

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Orders::getUserId, userId);

        ordersService.page(iPage, queryWrapper);

        List<Orders> ordersList = iPage.getRecords();

        long total = iPage.getTotal();

        List<OrdersDto> ordersDtos = new ArrayList<>();

        for (Orders orders : ordersList) {

            OrdersDto ordersDto = new OrdersDto();

            Long ordersId = orders.getId();

            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();

            queryWrapper1.eq(OrderDetail::getOrderId, ordersId);

            List<OrderDetail> list = orderDetailService.list(queryWrapper1);

            BeanUtils.copyProperties(orders, ordersDto);

            ordersDto.setOrderDetails(list);

            ordersDtos.add(ordersDto);

        }

        Map<String, Object> map = new HashMap();
        map.put("records", ordersDtos);
        map.put("total", total);
        map.put("pages", iPage.getPages());
        map.put("size", iPage.getSize());
        map.put("current", iPage.getCurrent());

        return R.success(map);

    }

    // @GetMapping("/userPage")
    public R selectByUserPages(Integer page, Integer pageSize, HttpServletRequest request) {

        IPage<Orders> iPage = new Page<>(page, pageSize);
        IPage<OrdersDto> dtoIPage = new Page<>();

        Long userId = (Long) request.getSession().getAttribute("user");

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Orders::getUserId, userId);

        ordersService.page(iPage, queryWrapper);

        //拷贝数据排除结果集
        BeanUtils.copyProperties(iPage, dtoIPage, "records");

        List<Orders> records = iPage.getRecords();

        List<OrdersDto> ordersDtos = new ArrayList<>();

        for (Orders orders : records) {

            OrdersDto ordersDto = new OrdersDto();

            Long ordersId = orders.getId();

            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();

            queryWrapper1.eq(OrderDetail::getOrderId, ordersId);

            List<OrderDetail> list = orderDetailService.list(queryWrapper1);

            BeanUtils.copyProperties(orders, ordersDto);

            ordersDto.setOrderDetails(list);

            ordersDtos.add(ordersDto);

        }

        dtoIPage.setRecords(ordersDtos);


        return R.success(dtoIPage);


    }


    @GetMapping("/page")
    public R selectByPage(Integer page, Integer pageSize, String number, @DateTimeFormat(pattern = "yyyy-mm-dd HH:mm:ss")
            LocalDateTime beginTime, @DateTimeFormat(pattern = "yyyy-mm-dd HH:mm:ss") LocalDateTime endTime) {

//        Integer page = (Integer) map.get("page");
//        Integer pageSize = (Integer) map.get("pageSize");
//        String number = (String) map.get("number");
//        LocalDateTime beginTime = (LocalDateTime) map.get("beginTime");
//        LocalDateTime endTime = (LocalDateTime) map.get("endTime");
        IPage<Orders> ordersIPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(number != null, Orders::getNumber, number);
        queryWrapper.le(endTime != null, Orders::getOrderTime, endTime).ge(beginTime != null, Orders::getOrderTime, beginTime);

        ordersService.page(ordersIPage);

        return R.success(ordersIPage);
    }

    //Excel导出功能
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {

        List<Orders> list = ordersService.list();

        ExcelUtils.exportExcel(list, "用户信息", "sheet1", Orders.class, "testDATA.xlsx", response);

    }
}
